/*
 * Copyright 2021 KylinSoft Co., Ltd.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "lid.h"

Lid::Lid(QObject *parent) : QObject(parent)
{
    qDebug() << "Lid init start";
    inhibitSystemdLogin();
    initLidConnection();
    m_lidIsClosed = readLidState();
}

Lid::~Lid() {}

void Lid::inhibitSystemdLogin()
{
    QDBusInterface manager(
        QStringLiteral(LOGIN1_SERVICE),
        QStringLiteral(LOGIN1_PATH),
        QStringLiteral(LOGIN1_MANAGER),
        QDBusConnection::systemBus());
    QDBusReply<QDBusUnixFileDescriptor> reply = manager.call(
        QStringLiteral("Inhibit"),
        QStringLiteral("handle-lid-switch"),
        QStringLiteral("powermanagment"),
        QStringLiteral("LidWatcher is in da house!"),
        QStringLiteral("block"));
    if (reply.isValid()) {
        logindLock = reply.value();
        qDebug() << "Inhibit got:" << logindLock.fileDescriptor();
    } else {
        qCritical() << "error code: " << INIT_LID_ERROR << ", msg: " << reply.error();
    }
}

void Lid::initLidConnection()
{
    bool result = QDBusConnection::systemBus().connect(
        LOGIN1_SERVICE, LOGIN1_PATH, LOGIN1_MANAGER, "PrepareForSleep", this, SLOT(dealWakeUpSignal(bool)));
    if (!result) {
        qCritical() << "error code: " << LID_CREATE_LOGIN1_CONNECTION_ERROR;
    }
    result = QDBusConnection::sessionBus().connect(
        UKUI_UPOWER_SERVICE,
        UKUI_UPOWER_PATH,
        UKUI_UPOWER_INTERFACE,
        "LidState",
        this,
        SLOT(dealLidWatcherMssage(bool)));
    if (!result) {
        qCritical() << "error code: " << LID_CREATE_UPOWER_CONNECTION_ERROR;
    }
}

bool Lid::readLidState()
{
    QDBusInterface iface(UPOWER_SERVICE, UPOWER_PATH, UPOWER_INTERFACE, QDBusConnection::systemBus());
    return iface.property("LidIsClosed").toBool();
}

void Lid::dealLidWatcherMssage(bool isClosed)
{
    qDebug() << "lid watcher, lid is closed:" << isClosed;
    m_lidIsClosed = isClosed;
    emit lidChanged(m_lidIsClosed);
}

void Lid::dealWakeUpSignal(bool isWakeup)
{
    qDebug() << "wake up , system wake up state:" << isWakeup;
    if (isWakeup) {
        return;
    }
    if (m_lidIsClosed) {
        qWarning() << "Sleep is awakened unexpectedly!";
        emit lidChanged(m_lidIsClosed);
    }
}
